<template>
  <BasicModal v-bind="$attrs" @register="registerGwModal" width="50%" destroyOnClose :title="title" @ok="handleSubmit">
    <BasicForm @register="registerGwForm"/>
  </BasicModal>
</template>

<script lang="ts" setup>

import {ref, computed, unref, reactive} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, FormSchema, useForm} from "@/components/Form";
import {useMessage} from "@/hooks/web/useMessage";
import {actProcessInsGetFirstNode, applyBizBusiness} from "@/views/activiti/modules/ActReModel.api";

const {createMessage} = useMessage()

const gwSchema: FormSchema[] = [
   {
     label:'是否显示审批人',
     field:'showAssign',
     component:'InputNumber',
     defaultValue:1,
     show:false
   },
   {
     label:'是否有下一审批人',
     field:'isGateway',
     component:'InputNumber',
     defaultValue:1,
     show:false
   },
   {
    label: '审批人',
    field: 'assignees',
    component: 'Select',
    required:true,
    componentProps: {
      options: [],
      mode:'multiple'
    },
    ifShow:({values})=>{
      return !!values.showAssign
    }
  },
   {
     label:'下一审批人',
     field:'nextApplyUser',
     component:'InputTextArea',
     defaultValue:'分支网关处不支持自定义选择下一审批人，将自动下发给所有可审批人。',
     componentProps:{
       disabled: true
     },
     ifShow:({values})=>{
       return !!values.isGateway
     }
   },
   {
     label:'优先级',
     field:'priority',
     component:'Select',
     defaultValue: '0',
     componentProps: {
      options: [
        {label: '普通', value: '0'},
        {label: '重要', value: '1'},
        {label: '紧急', value: '2'}
      ]
    }
   },
   {
      label:'系统消息通知',
      field: 'sendMessage',
      defaultValue:1,
      component: 'JSwitch',
      componentProps:{
        options:[1,0]
      }
    },
   {
      label:'短信通知',
      field: 'sendSms',
      defaultValue:0,
      component: 'JSwitch',
      componentProps:{
        options:[1,0],
        disabled:true
      }
    },
   {
      label:'邮件通知',
      field: 'sendEmail',
      defaultValue:0,
      component: 'JSwitch',
      componentProps:{
        options:[1,0],
        disabled:true
      }
    },
 ]

//设置标题
const title = '提交申请'
// Emits声明
const emit = defineEmits(['register','success']);
const labelCol = reactive({
  xs: { span: 24 },
  sm: { span: 7 },
});
const wrapperCol = reactive({
  xs: { span: 24 },
  sm: { span: 16 },
});
const showAssign = ref(false);
const applyForm = reactive<Record<string, any>>({
  title:'',
  procDefId:null,
  procDeTitle:null,
  processKey:null,
  tableName:null,
  tableId:null,
  priority: '0',
  assignees: [],
  sendMessage: 1,
  showAssign:0,
  isGateway:0
});

const [registerGwForm, {setProps,resetFields, setFieldsValue, validate,updateSchema}] = useForm({
    schemas: gwSchema,
    showActionButtonGroup: false,
    baseColProps: {span: 24}
});


//表单赋值
const [registerGwModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  await resetFields();
  setModalProps({confirmLoading: false,showCancelBtn:true,showOkBtn:true,cancelText:'取消'});
  initGateWay(data.record)
});


function initGateWay(record){
  if (!record.procDefId || record.procDefId == 'null') {
    createMessage.error('流程定义为空')
    return;
  }
  applyForm.tableId = record.tableId;
  applyForm.procDefId = record.procDefId;
  applyForm.tableName = record.tableName
  applyForm.procDeTitle = record.procDeTitle
  applyForm.processKey = record.processKey
  //此处record.title如果没有值 审批标题会显示不完整
  applyForm.title = `${record.procDeTitle}-${record.title}`;

  actProcessInsGetFirstNode({ procDefId: record.procDefId, tableId: record.tableId, tableName: record.tableName }).then((result) => {
    console.log('actProcessInsGetFirstNode:::', JSON.stringify(result));
    let error = ''
    let assigneeList = []
    if (result.type == 3 || result.type == 4) {
      applyForm.showAssign = 0;
      applyForm.isGateway = 1;
      setFieldsValue({
        ...applyForm
      })
      return;
    }
    applyForm.isGateway = 0;
    if (result.users && result.users.length > 0) {
      assigneeList = result.users;
      let ids = [];
      result.users.forEach((e) => {
        ids.push(e.username);
        return e.username;
      });
      applyForm.assignees = ids;
      applyForm.showAssign = 1;
    } else {
      applyForm.assignees = [];
      applyForm.showAssign = 1;
      error = '审批节点未分配候选审批人员，请联系管理员！';
    }
    if (error) {
      createMessage.error(error);
      return;
    }
    updateSchema({
      field:'assignees',
      componentProps:{
        fieldNames:{label:'realname',value:'username'},
        options:assigneeList
      }
    })
    setFieldsValue({
      ...applyForm
    })
    console.log('显示提交审核');
  });
}
//表单提交事件
async function handleSubmit(v) {
    try {
      let values = await validate();
      const params = Object.assign(applyForm,values)
      applyBizBusiness(params).then((res) => {
        if (res.success) {
          createMessage.success('操作成功');
          closeModal();
          emit('success');
        } else {
          createMessage.error(res.message);
        }
      });
    } finally {
        setModalProps({confirmLoading: false});
    }
}
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
